from fastapi import APIRouter, Depends
import sympy
import math
from backend.app.app.api.api_v1.user import verify_token_user
from backend.app.app.api.api_Hu.crud.pro.tb_userpro_input import get_query_data, get_name_year_public
from backend.app.app.crud_pro.tb_userpro_base import copy_page
from backend.app.app.api.api_Hu.models.dvpunithist import data, data1, data_save, data_query, data_page, PlanProj
from backend.app.app.api.api_Hu.crud.pub.tb_profit_analysis import save_project_db, query_data, get_p_id, get_u_id, updata_project_db, get_p_id_u, get_dvpunit_planproj
from backend.app.app.api.calculation.evaluation_calculation import calculation_critical_value


dvpunithist_router = APIRouter(prefix="/dvpunithist", tags=["措施单元盈亏平衡分析"])


@dvpunithist_router.post("/read_data", name="读取页面数据，临界值，盈亏结果，敏感参数")  #
async def read_data(trans_data: data_page, ver=Depends(verify_token_user)):
    data_q = query_data(user_Id=trans_data.user_id, Pro_Id=trans_data.user_id)
    return {"page_data": data_q, "verify": ver}
    # data_dist = {"user_id": data_q[0][0], "project_id": data_q[0][1], "dvpUnit_Name": data_q[0][2], "stimType_Name": data_q[0][3],
    #              "year": data_q[0][4], "calcu_type": data_q[0][5],
    #              "analysis_data": data_q[0][6], "parm_set_data": data_q[0][7], "OilPriceCritical": data_q[0][8],
    #              "IncreOilCritical": data_q[0][9],
    #              "StimCostCritical": data_q[0][10], "Stim_WellNumber_Valid": data_q[0][11],
    #              "Stim_WellValidRatio": data_q[0][12], "Stim_ValidPeriod_Average": data_q[0][13], "Stim_IncreOil_Average": data_q[0][14],
    #              "StimOil_CommodityRatio": data_q[0][15], "Oil_Price": data_q[0][16], "OilSale_TotalTaxRatio": data_q[0][17],
    #              "Money_Discount": data_q[0][18], "Oil_OprCost": data_q[0][19], "StimCost_Average": data_q[0][20]}


@dvpunithist_router.post("/save_data", name="保存页面数据，临界值，盈亏结果，")  #
async def save_data(input_data: data_save, ver=Depends(verify_token_user)):
    # input_data = {"User_ID":data.User_ID,"Proj_ID":data.Proj_ID,"DvpUnit_Name":data.dvpUnit_Name,"Year":data.year,
    #                "StimType_Name":data.stimType_Name,"Stim_WellNumber_Valid":data.Stim_WellNumber_Valid,
    #               "Stim_WellValidRatio":data.Stim_WellValidRatio,"Stim_ValidPeriod_Average":data.Stim_ValidPeriod_Average,
    #                "Stim_IncreOil_Average":data.Stim_IncreOil_Average,"StimCost_Average":data.StimCost_Average,
    #               "Oil_OprCost":data.Oil_OprCost,"Oil_Price":data.Oil_Price,
    #                "StimOil_CommodityRatio":data.StimOil_CommodityRatio,"OilSale_TotalTaxRatio":data.OilSale_TotalTaxRatio,
    #               "Money_Discount":data.Money_Discount,"Remark":''}
    u_id = get_u_id()
    p_id = get_p_id()
    list_u = []
    list_p = []
    for i in range(len(u_id)):
        list_u.append(u_id[i][0])
        list_p.append(p_id[i][0])
    if input_data.User_ID in list_u:
        if input_data.Proj_ID in list_p:
            result_up = updata_project_db(s_data=input_data)
            return {"result_save": result_up, "verify": ver}
            # for j in range(1,len(list_p)):
            #     if int(list_p[j]) - int(list_p[j-1]) != 1:
            #         id = int(list_p[j-1]) + 1
            #         input_data.Proj_ID = str(id)
            #         break
            # if j+1 == len(list_p):
            #     input_data.Proj_ID = str(j+2)
        else:
            result_add_o = save_project_db(s_data=input_data)

            return {"result_save": result_add_o, "verify": ver}
    else:
        result_add_o = save_project_db(s_data=input_data)
        return {"result_save": result_add_o, "verify": ver}


@dvpunithist_router.post("/analysis_calculation", name="分析盈亏计算")
async def analysis_calculation(trans_data: data1, ver=Depends(verify_token_user)):
    StimNPV = []
    pa = trans_data.parameter_set
    ValidYears = math.ceil(trans_data.Stim_ValidPeriod_Average / 365)
    IncreOilPy = trans_data.Stim_IncreOil_Average / ValidYears
    ic = trans_data.Money_Discount / 100
    re = 0
    for k in range(1, ValidYears + 1):
        re += (1 - ic) ** k
    for i in pa:
        StaticGainsPy = IncreOilPy * (i * trans_data.StimOil_CommodityRatio / 100 * (
            1 - trans_data.OilSale_TotalTaxRatio / 100) - trans_data.Oil_OprCost)

        temp = re * StaticGainsPy - trans_data.StimCost_Average
        temp.__float__()
        StimNPV.append(temp)

    return {"StimNPV": StimNPV, "verify": ver}


@dvpunithist_router.post("/calculation_critical_value_oilprice",
                         name="计算敏感参数-油价")
async def cal_cri_value_oilpricd(trans_data: data, ver=Depends(verify_token_user)):
    value_stimcost = None
    value_increoil = None
    value_oilprice = None
    a = calculation_critical_value.set_data(
        calculation_critical_value, trans_data)
    if a:
        value_stimcost = calculation_critical_value.stimcost_critical_value(
            calculation_critical_value)  # 临界作业成本
        value_increoil = calculation_critical_value.increoil_critical_value(
            calculation_critical_value)  # 临界措施增油
        value_oilprice = calculation_critical_value.oil_critical_value(
            calculation_critical_value)  # 临界油价

    OilPrice: float = trans_data.Oil_Price

    parm = []
    if OilPrice > value_oilprice:
        PriceStep = 100 * math.ceil(value_oilprice / 1000)
        for k in range(1, 11):
            OilPriceSensi_k = PriceStep * k

            parm.append(OilPriceSensi_k)
        PriceStep = 100 * math.ceil((OilPrice * 1.2 - value_oilprice) / 1000)
        for k in range(11, 21):
            OilPriceSensi_k = parm[9] + PriceStep * (k - 10)
            parm.append(OilPriceSensi_k)
    else:
        PriceStep = 100 * math.ceil(value_oilprice / 1000)
        for k in range(1, 11):
            OilPriceSensi_k = PriceStep * k
            parm.append(OilPriceSensi_k)
        PriceStep = 100 * math.ceil((value_oilprice * 1.5 - OilPrice) / 1000)
        for k in range(11, 21):
            OilPriceSensi_k = parm[9] + PriceStep * (k - 10)
            parm.append(OilPriceSensi_k)
    print(parm)
    print(type(parm))
    re_parm = []
    for i in parm:
        a = sympy.core.numbers.Integer.__int__(i)
        re_parm.append(a)

    value_oilprice = str(value_oilprice)
    value_increoil = str(value_increoil)

    return {"value_stimcost": value_stimcost, "value_increoil": value_increoil,
            "value_oilprice": value_oilprice, "parameter_set": re_parm, "verify": ver}  # ,"verify":ver


@dvpunithist_router.post("/calculation_critical_value_increoil",
                         name="计算敏感参数-措施增油")
async def cal_cri_value_increoil(trans_data: data, ver=Depends(verify_token_user)):  #
    value_stimcost = None
    value_increoil = None
    value_oilprice = None
    a = calculation_critical_value.set_data(
        calculation_critical_value, trans_data)
    if a:
        value_stimcost = calculation_critical_value.stimcost_critical_value(
            calculation_critical_value)  # 临界作业成本
        value_increoil = calculation_critical_value.increoil_critical_value(
            calculation_critical_value)  # 临界措施增油
        value_oilprice = calculation_critical_value.oil_critical_value(
            calculation_critical_value)  # 临界油价

    IncreOil: float = trans_data.Stim_IncreOil_Average

    parm = []
    if IncreOil > value_increoil:
        PriceStep = 100 * math.ceil(value_increoil / 1000)
        for k in range(1, 11):
            OilPriceSensi_k = PriceStep * k
            a = OilPriceSensi_k.__int__()
            parm.append(a)
        PriceStep = 100 * math.ceil((IncreOil * 1.2 - value_increoil) / 1000)
        for k in range(11, 21):
            OilPriceSensi_k = parm[9] + PriceStep * (k - 10)
            a = OilPriceSensi_k.__int__()
            parm.append(a)
    else:
        PriceStep = 100 * math.ceil(value_increoil / 1000)
        for k in range(1, 11):
            OilPriceSensi_k = PriceStep * k
            a = OilPriceSensi_k.__int__()
            parm.append(a)
        PriceStep = 100 * math.ceil((value_increoil * 1.5 - IncreOil) / 1000)
        for k in range(11, 21):
            OilPriceSensi_k = parm[9] + PriceStep * (k - 10)
            a = OilPriceSensi_k.__int__()
            parm.append(a)

    value_oilprice = str(value_oilprice)
    value_increoil = str(value_increoil)
    return {"value_stimcost": value_stimcost, "value_increoil": value_increoil,
            "value_oilprice": value_oilprice, "parameter_set": parm, "verify": ver}


@dvpunithist_router.post("/calculation_critical_value_stimcost",
                         name="计算敏感参数-作业成本")
async def cal_cri_value_stimcost(trans_data: data, ver=Depends(verify_token_user)):
    value_stimcost = None
    value_increoil = None
    value_oilprice = None
    a = calculation_critical_value.set_data(
        calculation_critical_value, trans_data)
    if a:
        value_stimcost = calculation_critical_value.stimcost_critical_value(
            calculation_critical_value)  # 临界作业成本   ,ver = Depends(verify_token_user)
        value_increoil = calculation_critical_value.increoil_critical_value(
            calculation_critical_value)  # 临界措施增油
        value_oilprice = calculation_critical_value.oil_critical_value(
            calculation_critical_value)  # 临界油价

    Stimcost: float = trans_data.StimCost_Average

    parm = []
    if Stimcost > value_stimcost:
        PriceStep = 10000 * math.ceil(value_stimcost / 100000)
        for k in range(1, 11):
            OilPriceSensi_k = PriceStep * k
            a = OilPriceSensi_k.__int__()
            parm.append(a)
        PriceStep = 10000 * \
            math.ceil((Stimcost * 1.2 - value_stimcost) / 100000)
        for k in range(11, 21):
            OilPriceSensi_k = parm[9] + PriceStep * (k - 10)
            a = OilPriceSensi_k.__int__()
            parm.append(a)
    else:
        PriceStep = 10000 * math.ceil(value_stimcost / 100000)
        for k in range(1, 11):
            OilPriceSensi_k = PriceStep * k
            a = OilPriceSensi_k.__int__()
            parm.append(a)
        PriceStep = 10000 * \
            math.ceil((value_stimcost * 1.5 - Stimcost) / 100000)
        for k in range(11, 21):
            OilPriceSensi_k = parm[9] + PriceStep * (k - 10)
            a = OilPriceSensi_k.__int__()
            parm.append(a)

    value_oilprice = str(value_oilprice)
    value_increoil = str(value_increoil)
    return {"value_stimcost": value_stimcost, "value_increoil": value_increoil, "value_oilprice": value_oilprice,
            "parameter_set": parm, "verify": ver}


@dvpunithist_router.post("/read_lib", name="读库")
async def read_lib(input_data: data_query, ver=Depends(verify_token_user)):
    data = get_query_data(
        dvpUnit_Name=input_data.name,
        stim_type=input_data.type,
        plan=input_data.plan,
        year=input_data.year
    )

    return {"data": data, "verify": ver}


@dvpunithist_router.post("/get_name_type_year", name="获取单元名称，措施类别，年度")
async def get_name_type_year(input_data: PlanProj, ver=Depends(verify_token_user)):
    data = get_name_year_public(input_data.DvpUnit_OilStim_PlanProj_Name)
    return {'data':data,"verify":ver}

@dvpunithist_router.post("/get_planproj", name="获取规划方案")
async def get_planproj(ver=Depends(verify_token_user)): # hzc增
    data = get_dvpunit_planproj()
    return {
        'data': data,
        'verify': ver
    }



